﻿using Sasa.QualityTools.CodeAnalysis.SearchEngine.Processing.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sasa.QualityTools.CodeAnalysis.SearchEngine.Processing
{
    internal class Parser
    {
        public IEnumerable<IToken> Parse(IEnumerable<IToken> tokens)
        {
            if (tokens == null || tokens.Count() == 0)
            {
                return new List<IToken>();
            }

            List<IToken> result = new List<IToken>();
            Stack<IToken> stack = new Stack<IToken>();

            foreach (IToken token in tokens)
            {
                if (token is Word)
                {
                    result.Add(token);
                }
                else if (token is RPar)
                {
                    while (!(stack.Peek() is LPar))
                    {
                        result.Add(stack.Pop());
                    }
                    stack.Pop();
                }
                else if (token is LPar)
                {
                    stack.Push(token);
                }
                else
                {
                    while (stack.Count > 0)
                    {
                        if (stack.Peek() is LPar || (((IOperatorToken)token).Priority < ((IOperatorToken)stack.Peek()).Priority))
                        {
                            break;
                        }
                        result.Add(stack.Pop());
                    }
                    stack.Push(token);
                }
            }

            while (stack.Count > 0)
            {
                result.Add(stack.Pop());
            }

            return result;
        }
    }
}
